package com.cloud.service.impl;

import com.cloud.Batch.Batch;
import com.cloud.mapper.Dealer;
import com.cloud.mapper.DealerMapper;
import com.cloud.service.DealerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: create by God of SJF
 * @version: v1.0
 * @description: com.cloud.service.impl
 * @date:2021/6/3
 */
@Service
public class DealerServiceImpl implements DealerService {


    @Autowired
    private DataSource dataSource;

    @Autowired
    DealerMapper dealerMapper;
    ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 3,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());

    public void updateAll() throws Exception {
        Connection connection = dataSource.getConnection();
        connection.setAutoCommit(false);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        try {
            for (int i = 1; i < 4; i++) {
                Batch batch = new Batch();
                batch.setId(i);
                batch.setCyclicBarrier(cyclicBarrier);
                batch.setConnection(connection);
                pool.execute(batch);
            }
        } catch (Exception e) {
            cyclicBarrier.reset();
        }
        cyclicBarrier.await();
        connection.commit();

    }



    @Override
    public void update(Integer id) {
        Dealer dealer = new Dealer();
        dealer.setId(id);
        dealer.setCode(String.valueOf(id));
        dealerMapper.updateByPrimaryKey(dealer);
    }

}
